package com.demon.auto.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.demon.auto.utils.CommonUtil;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * MybatisPlus 自动填充配置
 *
 * @version 1.0
 * @author huangrz
 * @date 2025/03/18 15:10
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    /**
     * 新增时填充字段
     * @param metaObject 元对象
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        // 创建人
        this.strictInsertFill(metaObject, "createCode", Long.class, CommonUtil.getCurrentUserIdCatch());
        // 创建时间
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        // 修改时间
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        // 修改人
        this.strictInsertFill(metaObject, "updateCode", Long.class, CommonUtil.getCurrentUserIdCatch());
    }

    /**
     * 修改时填充字段
     * @param metaObject 元对象
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        // 修改时间
        this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
        // 修改人
        this.setFieldValByName("updateCode", CommonUtil.getCurrentUserIdCatch(), metaObject);
    }

}
